package com.kky.pp.activity.home

import UserUtil
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.custom.base.base.SDBaseEvent
import com.kky.pp.dot.AFDotLogUtil
import com.kky.pp.common.Constant
import com.kky.pp.R
import com.kky.pp.entity.BaseEntity
import com.kky.pp.entity.IMTokenGetEntity
import io.rong.imkit.event.EnumEventTag
import com.kky.pp.rongyun.RongConfigUtil
import com.kky.pp.http.CommonRequest
import com.custom.base.config.BaseConfig
import com.custom.base.entity.OkHttpBodyEntity
import com.custom.base.http.OkHttpFromBoy
import com.custom.base.http.OkHttpManager
import com.custom.base.http.OkHttpResoutCallBack
import com.custom.base.http.SDOkHttpResoutCallBack
import com.custom.base.mvp.MVPBaseActivity
import com.custom.base.util.ToastUtil
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.messaging.FirebaseMessaging
import com.gyf.immersionbar.ImmersionBar
import com.luck.picture.lib.immersive.ImmersiveManager
import io.rong.imkit.SpName
import com.kky.pp.pay.GooglePayUtils
import com.kky.pp.activity.tab.BottomNavigationView
import com.kky.pp.activity.tab.TabHelper
import com.kky.pp.databinding.ActivityHomeBinding
import com.n_add.android.model.BottomTabViewModel
import io.rong.imkit.entity.OrderCreateEntity
import io.rong.imkit.utils.RouteUtils
import io.rong.imlib.RongCoreClient
import io.rong.imlib.RongIMClient


/**
 * 作者：
 * 时间：
 * 描述：主页
 */
class HomeActivity : MVPBaseActivity<HomeContract.View, HomePresenter,ActivityHomeBinding>(ActivityHomeBinding::inflate), HomeContract.View {
    override fun bindLayout(): Int {
        return R.layout.activity_home
    }


    override fun initView() {
        if (BaseConfig.getInstance.getString(SpName.token,"")!=""){
            GooglePayUtils.instance
        }
        homeTabBottomNavs.setBottomTabModelList(TabHelper.getBottomTabModelList())
            .setOnBottomTabClickListener(object :BottomNavigationView.OnBottomTabClickListener{
                override fun onTabClick(tabIndex: Int, bottomTabViewModel: BottomTabViewModel?) {
                    homeTabBottomNavs.setBackgroundColor(if (tabIndex==0)ContextCompat.getColor(this@HomeActivity,R.color.color_0F0F1C) else ContextCompat.getColor(this@HomeActivity,R.color.color_1F2635))
                    mPresenter?.setIndex(tabIndex)
                }
            }).init()

        //获取FCM的push token
        FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
            if (!task.isSuccessful) {
                return@OnCompleteListener
            }

            val token = task.result
            OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                override fun addBody(requestBody: OkHttpBodyEntity) {
                    requestBody.setPost(Constant.user_push_token_url)
                    requestBody.add("sourceType",1)
                    requestBody.add("token",token)
                }

            },object : SDOkHttpResoutCallBack<BaseEntity>(false) {
                override fun onSuccess(entity: BaseEntity) {

                }

            })
        })

        OkHttpManager.instance.setHttpCodeListener(object : OkHttpResoutCallBack.OnHttpCode {
            override fun code(code: Int, msg: String, url: String) {
                when (code) {
                    700 -> {
                        Toast.makeText(mActivity,mActivity.getString(R.string.account_logout_tip),Toast.LENGTH_SHORT).show()
                        UserUtil.out(mActivity)
                    }
                }
            }
        })

        RouteUtils.registerActivity(RouteUtils.RongActivityType.ConversationListActivity, HomeActivity::class.java)
    }
    override fun setFullScreen(): Boolean {
        return true
    }
    override fun onEventMainThread(event: SDBaseEvent) {
        when (EnumEventTag.valueOf(event.tagInt)) {
            EnumEventTag.INDEX_MATCH_REFRESH_DATA -> {
//                mPresenter?.getMatchList()
            }
            EnumEventTag.INDEX_TO_WLM -> {
                mPresenter?.goIndex(1)
            }
            EnumEventTag.BUY_MEMBER_CHAT -> {
                mPresenter?.goIndex(1)
            }
            EnumEventTag.REFRESH_WLM_LIKE_SIZE -> {
                mPresenter?.setWLMLikeSize(if (event.data!=null)event.data.toString().toInt() else 0 )
            }

            EnumEventTag.SHOW_NOTIFICATION_DIALOG -> {
                mPresenter?.showNotificationDialog(if (event.data!=null)event.data.toString() else "" )
            }
            EnumEventTag.WLM_REFRESH -> {
                mPresenter?.getWLMData()
            }
            EnumEventTag.SEND_VIP_NOTICE -> {
                CommonRequest.sendVipNotice(event.data.toString())
            }
            EnumEventTag.REFRESH_ME_BOTTOM_AVATAR->{
                mPresenter?.loadMeBottomAvatar(event.data.toString())
            }
            EnumEventTag.PAY_RESULT -> {
                try {
                    if (event.data.toString()!="") {
                        val orderCreateEntity = event.data as OrderCreateEntity
                        AFDotLogUtil().addPurchaseEvent(this, orderCreateEntity.data.payableAmount, orderCreateEntity.data.productCode)
                    }
                }catch (e:Exception){

                }

            }


            else -> {

            }
        }

    }
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
//        bottomView.saveInstanceState(outState)
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mPresenter?.onCreate(savedInstanceState,this)
        ImmersiveManager.translucentStatusBar(
            this@HomeActivity,
            true
        )
        if (RongCoreClient.getInstance().currentConnectionStatus.ordinal== RongIMClient.ConnectionStatusListener.ConnectionStatus.UNCONNECTED.ordinal){
            OkHttpManager.instance.requestInterface(object :OkHttpFromBoy{
                override fun addBody(requestBody: OkHttpBodyEntity) {
                    requestBody.setPost(Constant.im_token_Url)
                }
            },object : SDOkHttpResoutCallBack<IMTokenGetEntity>() {
                override fun onSuccess(parms: IMTokenGetEntity) {
                    RongConfigUtil.reConnectIM(parms.data.token)
                }

                override fun onFailure(code: Int, msg: String) {
                }
            })
        }
    }
    override fun onResume() {
        super.onResume()
//        mPresenter?.onResume()
        ImmersionBar.with(this).statusBarDarkFont(false).init()
    }

    private var centerPosition: Int=0
    private var mExitTime: Long = 0
    override fun onBackPressed() {
        if (System.currentTimeMillis() - mExitTime > 2000) {
            ToastUtil.toast("Press exit again!")
        } else {
            Runtime.getRuntime().exit(0)
        }
        mExitTime = System.currentTimeMillis()
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mPresenter?.onActivityResult(requestCode, resultCode, data)
    }

    override val homeTabBottomNavs: BottomNavigationView
        get() = viewBinding.homeTabBottomNav


}